{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 自定义模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mindspore import nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class AlexNet(nn.Cell):\n",
    "    def __init__(self, num_classes=1000,dropout=0.5):\n",
    "        super().__init__()\n",
    "        self.features = nn.SequentialCell(\n",
    "            nn.Conv2d(3, 64, kernel_size=11, stride=4, pad_mode='pad', padding=2),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "            nn.Conv2d(64, 192, kernel_size=5, pad_mode='pad', padding=2),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "            nn.Conv2d(192, 384, kernel_size=3, pad_mode='pad', padding=1),\n",
    "            nn.ReLU(),\n",
    "            nn.Conv2d(384, 256, kernel_size=3, pad_mode='pad', padding=1),\n",
    "            nn.ReLU(),\n",
    "            nn.Conv2d(256, 256, kernel_size=3, pad_mode='pad', padding=1),\n",
    "            nn.ReLU(),\n",
    "            nn.MaxPool2d(kernel_size=3, stride=2),\n",
    "        )\n",
    "        self.classifier = nn.SequentialCell(\n",
    "            nn.Dropout(p=dropout),\n",
    "            nn.Dense(256 * 6 * 6, 4096),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(p=dropout),\n",
    "            nn.Dense(4096, 4096),\n",
    "            nn.ReLU(),\n",
    "            nn.Dense(4096, num_classes),\n",
    "        )\n",
    "    def construct(self, x):\n",
    "        x = self.features(x)\n",
    "        x = x.view(x.shape[0], 256 * 6 * 6)\n",
    "        x = self.classifier(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import mindspore\n",
    "from mindspore import Tensor\n",
    "\n",
    "x = Tensor(np.random.randn(1, 3, 224, 224), mindspore.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.028577987\n"
     ]
    }
   ],
   "source": [
    "network = AlexNet()\n",
    "logits = network(x)\n",
    "print(logits.max())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
